qui(function(require, exports, module) {
    News.Edit = function(options) {
        this.dao = News.Dao;
        this.options = $.extend(true, {}, options);
        this.modify = Com.url.getQueryValue("modify",location.href);

        this.util = News.Util || {};
        this.config = News.config || {};
        this.construct = options.construct || function() {
            this.init();
        };
        this.config = $.extend({}, options.config);
        // 放在最下方立即执行
        this.construct.call(this);
    };

    News.Edit.prototype = {
        initConfig: function() {
			return true;
		},
        init: function() {
        },

        run: function() {
            var self = this;
            var $container = self.options.$container;
            self.init();
            self.initConfig();

			self.bindEvent();
			self.perpareData();
            self.initSuggest();
            self.fillForm();
        },

        perpareData: function() {
            var self = this;
            var username = $("div.user a.name").html();
            var requestData = {url: News.urlConfig.machinelistUrl, type: "get",
                                                params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                                              };
            self.dao.redirect({"request": JSON.stringify(requestData), "timeSign": new Date().getTime()}, function (data) {
                var hasDataRegion = [];

                if (data != null && data.response != null && data.response.list) {
                    $.each(data.response.list, function (index, obj) {
                        if (obj[1] >= 0 && obj[1] <= 2) {
                            if (hasDataRegion.indexOf(obj[1]) == -1) {
                                hasDataRegion.push(obj[1]);
                            }

                            News.Config.IP_LINK_AREA[obj[0]] = obj[1];
                            News.Config.IP_LINK_CH_AREA[obj[0]] = News.Config.REGION_CH_LIST[obj[1]]
                        }
                    });
                } else {
                    console.log("wait to do");
                }
            });
        },

        fillForm: function () {
            var programId = News.Util.getUrlId("programId");
            var self = this;
            if (programId != null) {
                self.dao.getList({program_id: programId}, function (data) {
                    var retValue = null;
                    if (data.code === 200 && data.response != null && data.response.list != null) {
                        retValue = data.response.list;
                        self.fillData(retValue[0]);
                    } else {
                        self.fillNoData();
                    }
                });
            } else {
                self.fillNoData();
            }
        },

        fillData: function (element) {
            var self = this;
            for (var key in element) {
                if (key == "repeat_info") {
                    var repeat_info_html = "";
                    var repeat_info_array = element[key];
                    for(var i=1; i<8; i++) {
                        var checked = "";
                        for(var j=0; j<repeat_info_array.length; j++) {
                            if (i == repeat_info_array[j]) {
                                checked ="checked='checked'";
                                break;
                            }
                        }
                        repeat_info_html += "<label class='checkbox inline'><input type='checkbox' id='repeat_info' name='repeat_info' value='" + i + "' " + checked + ">" + PreSet.Config.REPEAT_INFO[i-1] + "</label>";
                    }
                    $('#repeat_info_div').html(repeat_info_html);
                } else {
                    self.options.$container.find("input[name=" + key + "]").val(element[key]);
                }
            }
        },
        fillNoData: function () {
            var self = this;
            var repeat_info_html = "";
            for(var i=1; i<8; i++) {
                var checked = "";
                repeat_info_html += "<label class='checkbox inline'><input type='checkbox' name='repeat_info' value='" + i + "' " + checked + ">" + PreSet.Config.REPEAT_INFO[i-1] + "</label>";
            }
            $('#repeat_info_div').html(repeat_info_html);
        },

        bindEvent: function() {
            var self = this;

			jQuery.validator.addMethod("isValidTime", function(value, element, param) {
				var isValidTime = function(timeStr) {
                    var date = '00:00';
                    var formatTime = /^(\d{2}):(\d{2})$/
                    if (!timeStr || (timeStr.length < date.length) || ('string' !== typeof timeStr) || !formatTime.test(timeStr)) {
                        return false;
                    }
                    try {
                        var parts = (timeStr || '').split(':');
                        if (parts.length > 2) {
                            return false;
                        }

                        var hour   = Number(parts[0]).toFixed(0);
                        var minute = Number(parts[1]).toFixed(0);

                        if ((parts[0].indexOf('.') != -1) || (parts[1].indexOf('.') != -1)) {
                            return false;
                        }
                        if (isNaN(hour) || isNaN(minute)) {
                            return false;
                        }
                        if ((hour>=0 && hour<24) && (minute >= 0 && minute<60)) {
                            return true;
                        }
                    } catch (e) {
                        console.log(e.message);
                    }
                    return false;
                };

				return isValidTime(value);
			});

            var $container = self.options.$container;
            var $submit = $container.find('#Submit');
            var validator = self.getValidator();

			$form = $container;
			$form.find('input[name="start_time"]').timepicker({
				onClose: function(selectedDate) {
					$form.find('input[name="start_time"]').timepicker("option", selectedDate);
				},
				timeFormat: 'HH:mm'
			});
			$form.find('input[name="stop_time"]').timepicker({
				onClose: function(selectedDate) {
					$form.find('input[name="stop_time"]').timepicker("option", selectedDate);
				},
				timeFormat: 'HH:mm'
			});
            $submit.on('click', function() {
                var _save = function(data) {
                    if (data.channel_id == "") {
                        $(document).tips({
                            content: "请在Suggest中选择所属电视台",
                            type: "error"
                        });
                        return;
                    }
                    if (typeof(data.repeat_info) == "undefined") {
                        $(document).tips({
                            content: "请至少选择一个播放日期",
                            type: "error"
                        });
                        return;
                    }
                    $(document).tips({
                        content: "页面提交中",
                        type: "loading"
                    });
                    if (data.program_id) {
                        self.edit(data);
                    } else {
                        self.add(data);
                    }
                };
				var success = validator.form();
                var data = self.getParam();

				if (success){
					_save(data);
				}

            });
        },
        initSuggest:function(){
            var self = this;
            var $container = self.options.$container;
            var type = 'properTitle';
            var tpl = '<div><div class="contract-item">' +
                                '<span class="contract-width100">${channel_name}</span>' +
                                '<span class="contract-width100">${channel_code}</span>' +
                                '<span class="contract-width80" >${server_region}</span>' +
                                '<span class="contract-width200">${channel_addr}</span>' +
                                '<span class="contract-width100">${channel_ip}</span>' +
                                '<span class="contract-width80" >${channel_status}</span>' +
                                '<span class="contract-width80" >${channel_type}</span>' +
                                '</div></div>';
            var title = {
                            channel_name: '所属电视台',
                            channel_code: '代号',
                            server_region: '服务器',
                            channel_addr: '流地址',
                            channel_ip: '服务器IP',
                            channel_status: '收录状态',
                            channel_type: '收费'
                        };
            var getHtmlByData = function(data) {
                                var htmls = [];
                                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                                return htmlStr.html();
                            };
            var titleHtml = getHtmlByData(title);
            var channelNameSuggest = {
                options:{
                    source:News.urlConfig.channelUrl,
                    header: titleHtml,
                    method: "get",
                    multiple: false,
                    validate: true,
                    clearInvalid: true,
                    noResult: '对不起，没有这个结果',
                    onblur: function() {
                        console.log('onblur');
                    },
                    onNoResult: function() {
                        console.log('noResult');
                    },
                    select: function(event, ui) {
                        if (ui && ui.item) {
                            $container.find('input[name="channel_code"]').val(ui.item.channel_code);
                            $container.find('input[name="channel_area"]').val(ui.item.channel_area);
                            $container.find('input[name="channel_ip"]').val(ui.item.channel_ip);
                            $container.find('input[name="channel_id"]').val(ui.item.channel_id);
                        }
                    },
                    parseValue: function() {
                        var val = this.element.val();
                        var ret = [];
                        if (val) {
                            var items = val.split(';');
                            $.each(items, function(i, item) {
                                item = item.split(',');
                                ret.push({
                                    value: item[1],
                                    id: item[0],
                                    label: item[1]
                                });
                            });
                        }
                        this._value('');
                        return ret;
                    },
                    getParam: function (term) {
                        var requestData = {type:0, from_client:true, channel_name: term, _: new Date().getTime()};
                        return requestData;
                    },

                    process: function(json) {
                        var data = json.response.list;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, {
                                value: item.channel_name
                            }, item, {
                                // displayName: item[type],
                                id: item.channel_id,
                                channel_status: News.Util.formatter.channel_status(item.channel_status),
                                channel_type: News.Util.formatter.freeType(item.freeType),
                                channel_area: News.Config.IP_LINK_AREA[item.channel_ip],
                                server_region: News.Config.IP_LINK_CH_AREA[item.channel_ip]
                            }));
                        });
                        return ret;
                    },

                    template: function (item) {

                        return getHtmlByData(item);
                    }
                }
            };
            $("input[name='channel_name']").suggest(channelNameSuggest.options);
        },

        getValidator: function() {
            var $container = this.options.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, News.Config.validator);

            return validator;
        },

        getParam: function() {
            var $container = this.options.$container;
            var self = this;
			var checkboxObj = null;
            var $elements = $.makeArray($container.prop('elements')).filter(function(item) {

				return true;
            });

			var checkboxVal = [];
            var name;
            var key;
			var params = {};

            $.each($elements, function() {
                name = this.name;
                if (name) {
                    if(name=='repeat_info') {
                        if(this.checked)
                        {
                            checkboxVal.push($(this).val());
                        }
                    } else if(name=='program_id' && $(this).val() == "") {

                    } else {
                        params[name] = $(this).val();
                    }
                }
            });

			if(checkboxVal.length!==0){
                params['repeat_info']=JSON.stringify(checkboxVal);//params['repeat_info'].join(',');
            }
            return params;
        },
        add: function(data) {
            this.dao.add(data, this.onSave);
        },
        edit: function(data) {
            var params = $.extend(true, {func : "modify_ablum"}, data);
            this.dao.modify(params, this.onSave);
        },

        onSave: function(json) {
            if (json.code == '200' && json.response.status == 0) {
                var url = '/epg/news_home.html';

                setTimeout(function() {
                    window.location.href = url;
                }, 2000);
                var html = '操作成功，系统将在两秒后跳转到节目页面,<a href="' + url + '" target="_self">立即跳转</a>';
                $(document).tips({
                    content: html,
                    type: "loading"
                });
            } else {
                $(document).tips({
                    content: json.response.error,
                    type: "error"
                });
            }

        },

    };

});
